package com.example.photo.aop;

import com.example.photo.common.AuthCheck;
import com.example.photo.common.ErrorCode;
import com.example.photo.exception.BusinessException;
import com.example.photo.utils.JwtTokenUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * 权限校验
 *
 * @author Lwh
 * @time 2023/03/27 00:59
 */
@Aspect
@Component
public class AuthInterceptor {
    @Around("@annotation(authCheck)")
    public Object doInterceptor(ProceedingJoinPoint joinPoint, AuthCheck authCheck) throws Throwable {
        RequestAttributes requestAttributes = RequestContextHolder.currentRequestAttributes();
        HttpServletRequest request = ((ServletRequestAttributes) requestAttributes).getRequest();

        String role = request.getHeader(JwtTokenUtils.ROLE_HEADER);
        if (!role.equals("1")){
            throw new BusinessException(ErrorCode.NO_AUTH, "无权限");
        }

        return joinPoint.proceed();
    }
}
